package com.cl.activity;

import java.lang.reflect.Method;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.format.Formatter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cl.safe.R;

public class CleanCacheActivity extends Activity {
	private ProgressBar progressBar1;
	private LinearLayout ll_container;
	private TextView tv_status;
	private PackageManager pm;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_clean_cache);
		progressBar1 = (ProgressBar) findViewById(R.id.progressBar1);
		ll_container = (LinearLayout) findViewById(R.id.ll_container);
		tv_status = (TextView) findViewById(R.id.tv_status);
		
		new Thread(){
			public void run() {
				pm = getPackageManager();
				List<PackageInfo> packInfos = pm.getInstalledPackages(0);
				progressBar1.setMax(packInfos.size());
				int progress = 0;
				for(final PackageInfo packInfo:packInfos) {
					String packName = packInfo.packageName;
					try {
						Method method = PackageManager.class.getMethod("getPackageSizeInfo"
								, String.class,IPackageStatsObserver.class);
						method.invoke(pm, packName, new MyObserver());
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								String appName = packInfo.applicationInfo.loadLabel(pm).toString();
								tv_status.setText("正在扫描：  "+appName);
							}
						});
						progress ++;
						progressBar1.setProgress(progress);
						try {
							Thread.sleep(50);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						tv_status.setText("扫描完毕");
					}
				});
			};
			
		}.start();
	}
	private class MyObserver extends IPackageStatsObserver.Stub {
		@Override
		public void onGetStatsCompleted(final PackageStats pStats, boolean succeeded)
				throws RemoteException {
			final long cache = pStats.cacheSize;
			long codeSize = pStats.codeSize;
			if(cache>0){
				//System.out.println("当前应用程序："+pStats.packageName+"有缓存："+Formatter.formatFileSize(getApplicationContext(), cache));
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
							try {
								Drawable icon = pm.getApplicationInfo(pStats.packageName, 0).loadIcon(pm);
								String name = pm.getApplicationInfo(pStats.packageName, 0).loadLabel(pm).toString();
								long size = cache;
								final String packname = pStats.packageName;
								View view = View.inflate(getApplicationContext(), R.layout.list_appcache_item, null);
								ImageView iv = (ImageView) view.findViewById(R.id.iv_icon);
								TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
								TextView tv_cache = (TextView) view.findViewById(R.id.tv_cache);
								iv.setImageDrawable(icon);
								tv_name.setText(name);
								tv_cache.setText("缓存大小："+Formatter.formatFileSize(getApplicationContext(), size));
								ImageView iv_delete = (ImageView) view.findViewById(R.id.iv_delete);
								iv_delete.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										Method[] methods = PackageManager.class.getMethods();
										for(Method method : methods){
											try {
												if("deleteApplicationCacheFiles".equals(method.getName())){
													method.invoke(pm, packname,new IPackageDataObserver.Stub() {
														@Override
														public void onRemoveCompleted(String packageName, boolean succeeded)
																throws RemoteException {
															
														}
													});
												}
											} catch (Exception e) {
												Intent intent = new Intent();
												intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
												intent.addCategory(Intent.CATEGORY_DEFAULT);
												intent.setData(Uri.parse("package:"+packname));
												startActivity(intent);
												e.printStackTrace();
											}
										}
									}
								});
								ll_container.addView(view, 0);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					}
				});
			}
		}
	}
	
	public void cleanAll(View view){
//		/freeStorageAndNotify
		Method[] methods = PackageManager.class.getMethods();
		for(Method method:methods){
			if("freeStorageAndNotify".equals(method.getName())){
				try {
					method.invoke(pm, Integer.MAX_VALUE, new IPackageDataObserver.Stub() {
						@Override
						public void onRemoveCompleted(String packageName,
								boolean succeeded) throws RemoteException {
							System.out.println(succeeded);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}
		}
	}
	
}
